// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()

// 云函数入口函数
exports.main = async (event, context) => {
  try {
    const { productId } = event
    
    if (!productId) {
      return {
        success: false,
        errMsg: '缺少商品ID参数'
      }
    }
    
    // 获取规格组信息
    const { data: specGroups } = await db.collection('specGroups')
      .where({
        productId
      })
      .orderBy('order', 'asc')
      .get()
    
    // 获取规格信息
    const { data: specs } = await db.collection('specs')
      .where({
        productId
      })
      .orderBy('order', 'asc')
      .get()
    
    // 将规格按组进行分类
    const groupedSpecs = {}
    specs.forEach(spec => {
      if (!groupedSpecs[spec.groupId]) {
        groupedSpecs[spec.groupId] = []
      }
      groupedSpecs[spec.groupId].push(spec)
    })
    
    // 将规格添加到对应的规格组中
    const result = specGroups.map(group => {
      return {
        ...group,
        specs: groupedSpecs[group._id] || []
      }
    })
    
    return {
      success: true,
      data: result
    }
  } catch (err) {
    return {
      success: false,
      errMsg: err.message
    }
  }
}